#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

require 'log4r'
include Log4r

@@log=Logger.new 'log'
@@log.outputters=Outputter.stdout

require 'socket'
require 'commands.rb'
require 'parser.rb'

@@log.info 'begin to listen connecting incoming'

@@server=TCPServer.new(30000)
def main
  while true
    Thread.new(@@server.accept) do |peer_socket|
      @@log.info "connect from: \n\t ip:#{peer_socket.peeraddr[3]} \n\t port:#{peer_socket.peeraddr[1]}"

      peer_socket.print "Welcome to you.This is a Linux admin server\n\n"


      try_count=0
      @@log.info "someone try to login"
      while true
        peer_socket.puts "please input your user name:"
        username=peer_socket.gets.chomp
        @@log.info "try username #{username}"
        peer_socket.puts "please input the user name's password"
        password=peer_socket.gets.chomp
        @@log.info "try password #{password}"
        if username=='admin' and password=="apple" then
          peer_socket.puts "I begin to service for you...."
          break
        else
          try_count+=1
          if try_count==3 then
            peer_socket.close
            Thread.exit
          end
        end
      end

      while peer_socket.gets
        @@log.info "Get input_string: #{$_}"

        if $_.chomp.length==0 then
          peer_socket.puts 'please input a command'
          next
        end

        command,args=parser $_
        @@log.info "command is:#{command}"
        @@log.info "argument is: #{args}  "

        begin
          response=Commands.do_command(command,args)
          peer_socket.print response
        rescue Exception => e
          peer_socket.puts "server exception\n"+e.to_s
          peer_socket.puts "line:"+$@.to_s
        end
        peer_socket.flush

      end

      @@log.info "connect closed"
      peer_socket.close
    end
  end
end

main()



